package action.user;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import org.hibernate.*;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import db.*;

@SuppressWarnings("serial")
public class TransactionAction extends ActionSupport{
	private db.Transaction tr;
	//private String tr_type;
	private String newTR_scId;
	private String new_trId;
	
	public db.Transaction getTr() {
		return tr;
	}
	public void setTr(db.Transaction tr) {
		this.tr = tr;
	}
	
	public String getNewTR_scId() {
		return newTR_scId;
	}
	public void setNewTR_scId(String newTRScId) {
		newTR_scId = newTRScId;
	}
	
	public String getNew_trId() {
		return new_trId;
	}
	public void setNew_trId(String newTrId) {
		new_trId = newTrId;
	}
	@SuppressWarnings("unchecked")
	public String add(){
		Map session = ActionContext.getContext().getSession();		
		Integer scId = Integer.parseInt(this.getNewTR_scId());
		ServiceContractDAO scDao = new ServiceContractDAO();
		ServiceContract temp_sc = scDao.findById(scId);
		Integer tr_uid = temp_sc.getUId();
		String userId = (String)session.get("userId");
		Integer uId = Integer.parseInt(userId);
		if (!tr_uid.equals(uId)){
			System.out.println("Wrong privilege!");
			return ERROR;
		}
		TransactionDAO trDao = new TransactionDAO();
		org.hibernate.Transaction trans = trDao.getSession().beginTransaction();
		db.Transaction trToAdd = new db.Transaction();		
		trToAdd.setServiceContract(temp_sc);
		trToAdd.setTrStatus(0);//0 for initial, 1 for in-progress, 2 for done(after sale)
		Date now = new Date();
		now.getTime();
		trToAdd.setTrDate(now);
		trToAdd.setTrType(0);//obsolete!
		trToAdd.setBids(null);// for now
		trToAdd.setTrDescription(tr.getTrDescription());
		trDao.save(trToAdd);
		trans.commit();
		
		org.hibernate.Transaction trans2 = scDao.getSession().beginTransaction();
		Set transactionSet = new HashSet();
		Set tempSet = temp_sc.getTransactions();
		if (tempSet !=null)
			transactionSet = tempSet;
		//transactionSet = temp_sc.getTransactions();
		transactionSet.add(trToAdd);
		temp_sc.setTransactions(transactionSet);
		trans2.commit();
		this.setNew_trId(trToAdd.getTrId()+"");
		return SUCCESS;
	}
}
